package org.phantom.demo.search;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.phantom.demo.api.SearchBean;
import org.phantom.demo.api.SearchHandler;
import org.phantom.demo.api.SearchParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/search")
public class SearchController {
	
	
	@Resource(name="handlers")
	private List<SearchHandler> handlers = null;
	
	@RequestMapping
	public ResponseEntity<List<? extends SearchBean>> doSearch(final String key){
		
		if(key==null||"".equals(key))
			return new ResponseEntity<List<? extends SearchBean>>(HttpStatus.BAD_REQUEST);
			
		
		List<SearchBean> list = new ArrayList<SearchBean>();
		
		for (SearchHandler handler : handlers) {
			list.addAll(handler.doSearch(new SearchParameter() {
				@Override
				public Object getSearchValue() {
					return key;
				}
			}));
		}
		if(list.size()==0)
			return new ResponseEntity<List<? extends SearchBean>>(HttpStatus.NOT_FOUND);
		return new ResponseEntity<List<? extends SearchBean>>(list, HttpStatus.OK);
	}
}
